﻿using System;
using System.Data;
using System.Data.SqlClient;
using FunctionalCLR.Core;

namespace FunctionalCLR.Shell.Databasing
{
    public class OpenDatabaseNode : FuncNode
    {
        public OpenDatabaseNode()
            : base("openDatabase")
        {
        }

        public override object Evaluate()
        {
            int length = Parameters.Count;
            if(Parameters.Count < 0) {
                throw new ArgumentException(
                    "usage: openDatabase(dbName, userName, password)");
            }

            string dbName = Convert.ToString(
                Parameters[length-1].Evaluate());
            string userName = Convert.ToString(
                Parameters[length-2]);
            string pwd = Convert.ToString(
                Parameters[length-3]);
            
            string connectionString = NewConnection(
                dbName, userName, pwd);

            SqlConnection conn = new SqlConnection(
                connectionString);
            conn.Open();

            return conn;
        }

        public string NewConnection(
            string serverName, string uid, string pwd)
        {
            SqlConnectionStringBuilder conStrbuilder = new SqlConnectionStringBuilder();
            conStrbuilder.DataSource = serverName;
            conStrbuilder.UserID = uid;
            conStrbuilder.Password = pwd;

            return conStrbuilder.ConnectionString;
        }

    }
}
